package com.app.shop.activitys;

import android.Manifest;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.app.shop.MyApplication;
import com.app.shop.R;
import com.app.shop.beans.DTBean;
import com.app.library.base.BaseActivity;
import com.app.library.beans.EventMessage;
import com.app.library.utils.GlideUtils;
import com.app.library.utils.StringUtil;
import com.app.library.utils.TimeUtil;
import com.app.library.utils.ToastUtil;
import com.app.library.utils.UserManager;
import com.app.library.widgts.LoadingDialog;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.engine.GlideEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.PermissionChecker;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

public class DTEditActivity extends BaseActivity {


    private TextView tvTitle;
    private ImageView imgv;
    private EditText edtTitle;
    private EditText edtContent;


    String path;
    DTBean dtBean;
    private Dialog mLoadingDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dt_edit);
        tvTitle= (TextView) findViewById(R.id.tv_title);
        imgv= (ImageView) findViewById(R.id.imgv);
        edtTitle= (EditText) findViewById(R.id.edt_title);
        edtContent= (EditText) findViewById(R.id.edt_content);

      ImageView  imgvreturn= (ImageView) findViewById(R.id.imgv_return);
       TextView tvok= (TextView) findViewById(R.id.tv_ok);

        imgv.setOnClickListener(this::onViewClicked);
        imgvreturn.setOnClickListener(this::onViewClicked);
        tvok.setOnClickListener(this::onViewClicked);
        //跳转相机动态权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }

        tvTitle.setText("发布动态");
        if (savedInstanceState != null) {
            // 被回收
        } else {
            clearCache();
        }
        mLoadingDialog = LoadingDialog.createLoadingDialog(this, true, "请稍后，图片上传中...");

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            dtBean = (DTBean) bundle.getSerializable("bean");
            edtTitle.setText(dtBean.title);
            edtContent.setText(dtBean.content);
            path = dtBean.pic;
            Glide.with(DTEditActivity.this).load(path).into(imgv);
        }
    }


    private void save() {

        String title = edtTitle.getText().toString();
        String content = edtContent.getText().toString();
        if (StringUtil.isEmpty(title)
                || StringUtil.isEmpty(content)
                || StringUtil.isEmpty(path)) {
            ToastUtil.showToast(this, "请完善信息");
            return;
        }

        if (dtBean == null) {

            DTBean bean = new DTBean();
            bean.d_id = System.currentTimeMillis() + "";
            bean.title = title;
            bean.content = content;
            bean.pic = (path);
            bean.create_time = (TimeUtil.getTodayData("yyyy-MM-dd HH:mm:ss"));
            bean.user_id = (UserManager.getUserId(this));
            bean.user_name = (UserManager.getUserName(this));
            bean.save();
            ToastUtil.showToast(this, "发布成功");
        } else {
            ContentValues values = new ContentValues();
            values.put("title", title);
            values.put("content", content);
            values.put("pic", path);
            DataSupport.updateAll(DTBean.class, values, "d_id=?", dtBean.d_id);
            ToastUtil.showToast(this, "修改成功");

            dtBean.title = title;
            dtBean.content = content;
            dtBean.pic = (path);

        }
        EventBus.getDefault().post(new EventMessage(EventMessage.REFRESH, dtBean));
        onBackPressed();
    }


    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.imgv_return:
                onBackPressed();
                break;
            case R.id.imgv:
                showPicSeleDialog();
                break;
            case R.id.tv_ok:
                save();
                break;

        }
    }


    /**
     * picSelector的相册相机界面
     * <p>
     * // 例如 LocalMedia 里面返回三种 path
     * // 1.media.getPath(); 为原图 path
     * // 2.media.getCutPath();为裁剪后 path，需判断 media.isCut();是否为 true
     * // 3.media.getCompressPath();为压缩后 path，需判断 media.isCompressed();是否为 true
     * // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
     */
    protected void showPicSeleDialog() {
        // 进入相册 以下是例子：不需要的api可以不写
        PictureSelector.create(DTEditActivity.this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                .isWeChatStyle(true) //仿微信面板
                .maxSelectNum(1)// 最大图片选择数量
                .isGif(true) //是否展示gif
                .queryMaxFileSize(20)  //图片最大大小  20Mb
                .enableCrop(true)  //是否裁剪
                .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .compress(true)// 是否压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .compressSavePath(getCompressPath())//压缩图片自定义保存地址
                //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }


    /**
     * 清空缓存包括裁剪、压缩、AndroidQToPath所生成的文件，注意调用时机必须是处理完本身的业务逻辑后调用；非强制性
     */
    private void clearCache() {
        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        if (PermissionChecker.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            //PictureFileUtils.deleteCacheDirFile(this, PictureMimeType.ofImage());
            PictureFileUtils.deleteAllCacheDirFile(this);
        } else {
            PermissionChecker.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PictureConfig.APPLY_STORAGE_PERMISSIONS_CODE);
        }
    }

    // 压缩后图片文件存储位置
    private String getCompressPath() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PictureSelector/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) { // 如果返回码是可以用的
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> mediaList = PictureSelector.obtainMultipleResult(data);
                    for (int i = 0; i < mediaList.size(); i++) {
                        if (mediaList.get(i) != null && mediaList.get(i).isCompressed()) { //压缩
                            // 1.media.getPath(); 为原图 path
                            // 2.media.getCutPath();为裁剪后 path，需判断 media.isCut();是否为 true
                            // 3.media.getCompressPath();为压缩后 path，需判断 media.isCompressed();是否为 true
                            path = mediaList.get(i).getCompressPath();  //压缩后的地址
                            //获取所有选择的图片
                            initUploadHttp(new File(path));

                        }
                        LoadingDialog.showDialog(mLoadingDialog);

                    }
                    //上传完毕

                    LoadingDialog.closeDialog(mLoadingDialog);


                    break;
            }
        }
    }

    String BASE_URL_SET_PIC = "http://120.79.198.127:8080/hello/setImage?picbeanstr=";
    String BASE_URL_GET_PIC = "http://120.79.198.127:8080/hello/getImage?name=";

    private void initUploadHttp(File file) {
        final String name = System.currentTimeMillis() + "";
        //拼接参数
        final PostRequest request = OkGo.post(BASE_URL_SET_PIC + name).tag(this);
        request.params("uploadFile", file);

        Log.v(MyApplication.TAG, "name :" + name.toString());
        request.execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                Log.v(MyApplication.TAG + "pic:", response.toString());
                Log.v(MyApplication.TAG + "pic url:", BASE_URL_GET_PIC + name);
                path = BASE_URL_GET_PIC + name;
                GlideUtils.getInstance().loadImage(DTEditActivity.this, path, imgv);
            }
        });
    }

}
